//
//  ChatViewModel 2.h
//  MiniWeChat
//
//  Created by ByteDance on 2025/6/24.
//

#import "ChatViewModel.h"
#import "DBStorageService.h"
#import "StrUtil.h"

@interface ChatViewModel ()

@end

@implementation ChatViewModel

- (instancetype)initWithConversation:(ConversationModel *)conversation {
    self = [super init];
    if (self) {
        NSArray<NSString *> *strs = [StrUtil splitConcatenatedString:conversation.id];
        DBStorageService *storage = [DBStorageService sharedInstance];
        self.messages = [NSMutableArray array];
        self.sender = [storage fetchUserById:[strs objectAtIndex:1]];
        self.receiver = [storage fetchUserById:[strs objectAtIndex:0]];
        self.conversation = conversation;
        
        [self startNotificationListening];
    }
    return self;
}

- (void)startNotificationListening {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleReceivedNewMessage:)
                                                 name:kNotificationReceivedNewMessage
                                               object:nil];
}

- (void)stopNotificationListening {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationReceivedNewMessage
                                                  object:nil];
}

- (void)handleReceivedNewMessage:(NSNotification *)notification {
    MessageModel *message = notification.userInfo[@"message"];
//    // 异步更新聊天会话信息
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        DBStorageService *storage = [DBStorageService sharedInstance];
//        [storage fetchConversationById:message.conversation_id completion:^(ConversationModel * _Nonnull conversation, NSError * _Nonnull error) {
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                conversation.last_msg_id = message.id;
//                conversation.last_msg_content = message.content;
//                conversation.last_msg_time = message.time;
//                [storage saveConversation:conversation];
//            });
//        }];
//    });
}

- (void)fetchMessages {
    DBStorageService *storage = [DBStorageService sharedInstance];
    // 1. 从本地数据库中获取数据
    NSArray<MessageModel *> *messages = [storage fetchMessagesByConversationId:self.conversation.id];
    // 2. 从网络请求中获取数据
    // 3. 异步更新网络数据至本地数据库
    // 4. 合并本地数据和网络数据并排序
    [self.messages removeAllObjects];
    [self.messages addObjectsFromArray:messages];
    [self sortMessages];
    
    // 发送通知让视图更新
    [self postMessagesUpdatedNotification];
}

- (void)sortMessages {
    
}

- (void)postMessagesUpdatedNotification {
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationMessagesUpdated object:self];
}

- (void)sendMessage:(NSString *)content {
    if (!content || content.length == 0) return;
    DBStorageService *storage = [DBStorageService sharedInstance];
    
    // 1. 创建新消息
    MessageModel *message = [[MessageModel alloc] init];
    message.id = [[NSUUID UUID] UUIDString];
    message.type = 1; // 文本消息 TODO 枚举
    message.sender = self.sender.id;
    message.receiver = self.receiver.id;
    message.conversation_id = self.conversation.id;
    message.content = content;
    message.time = [[NSDate date] timeIntervalSince1970];
    
    // 2. 保存至本地数据库
    [storage saveMessage:message];
    [self.messages addObject:message];
    // 3. 异步 网络请求 同时更新状态
    // 4. 通知 聊天会话接收到新消息事件
    
    [self postMessagesUpdatedNotification];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationReceivedNewMessage object:self userInfo:@{@"message":message, @"isMine":@YES}];
    
    // 模拟对方回复
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        MessageModel *replyMessage = [[MessageModel alloc] init];
        replyMessage.id = [[NSUUID UUID] UUIDString];
        replyMessage.sender = self.receiver.id;
        replyMessage.receiver = self.sender.id;
        replyMessage.conversation_id = self.conversation.id;;
        replyMessage.content = [NSString stringWithFormat:@"我收到了你的消息: %@", content];
        replyMessage.time = [[NSDate date] timeIntervalSince1970];
        
        [storage saveMessage:replyMessage];
        [self.messages addObject:replyMessage];
        [self postMessagesUpdatedNotification];
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationReceivedNewMessage object:self userInfo:@{@"message":replyMessage, @"isMine":@NO}];
    });
}

- (NSInteger)numberOfMessages {
    return _messages.count;
}

- (MessageModel *)messageAtIndex:(NSInteger)index {
    if (index < 0 || index >= _messages.count) return nil;
    return _messages[index];
}

- (void)dealloc {
    [self stopNotificationListening];
}

@end
